﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

using Factonomy.AzureUtility.Core;
using Factonomy.AzureUtility.Core.Storage;
using Factonomy.AzureUtility.Core.StorageHelpers;

namespace Factonomy.AzureUtility.Controls
{
    class ContainersContextMenu : BaseContextMenu
    {
        public event TreeViewItemHelperDelegate ContainerAdded;

        protected virtual void OnContainerAdded(TreeViewItemHelper helper)
        {
            if (ContainerAdded != null)
                ContainerAdded(helper);
        }

        public ContainersContextMenu()
        {
            MenuItem item = new MenuItem();
            item.Header = "Add Container";
            item.Click += new System.Windows.RoutedEventHandler(AddContainer);
            this.Items.Add(item);
        }

        void AddContainer(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                TreeViewItem item = (TreeViewItem)((Popup)((ContextMenu)(((MenuItem)sender).Parent)).Parent).PlacementTarget;
                if (item != null)
                {
                    if (item.Tag != null)
                    {
                        TreeViewItemHelper helper = item.Tag as TreeViewItemHelper;
                        this._helper = helper;
                        Dialogs.StringPrompt dialog = new Dialogs.StringPrompt();
                        dialog.ReturnValue += new StringPromptDelegate(dialog_ReturnValue);
                        dialog.Owner = Application.Current.Windows[0];
                        dialog.ShowDialog();

                    }
                }
            }
            catch (Exception ex)
            {

            }
            
        }

        void dialog_ReturnValue(string value, Dialogs.StringPrompt dialog)
        {
            ConfigAccount account = Config.Instance.GetAccount(this._helper.AccountName);
            BlobHelper.Instance.AddContainer(account, value);
            this._helper.Container = value;
            dialog.Close();
            this.OnContainerAdded(this._helper);
            this._helper = null;
        }

    }
}
